package com.pizza.server.rmi;

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;

import org.hibernate.Session;

import com.mcol.common.rmi.Logowanie;
import com.pizza.hibernate.Adres;
import com.pizza.hibernate.SessionFactoryUtil;
import com.pizza.hibernate.User;

public class LogowanieServer extends UnicastRemoteObject implements Logowanie{
	Session session;
	int id;
	Integer balance;
	public LogowanieServer(Integer balance) throws RemoteException {
		super();
		// TODO Auto-generated constructor stub
		 session = SessionFactoryUtil.getSessionFactory().getCurrentSession();
	        session.beginTransaction();
	        session.getTransaction().commit();
	        this.balance=balance;
	}

	@Override
	public User zaloguj(String login, String password)
			throws RemoteException {
		session = SessionFactoryUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();
//        Query q = session.createQuery("from UserServer where login like :login");
//        q.setParameter("login", arg1)
//       q.uniqueResult();
        for (User user : (ArrayList<User>) session.createQuery("from User").list()) {
			if(user.getLogin().equalsIgnoreCase(login))
				if(user.getPassword1().equalsIgnoreCase(password))
					{
						
						session.getTransaction().commit();
						return user;
					}
		}
        session.getTransaction().commit();
		return null;
	}

	@Override
	public Adres pobierzAdres(int id) throws RemoteException {
		session = SessionFactoryUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        Adres b =(Adres) session.createQuery("from Adres WHERE id="+id).list().get(0);
        session.getTransaction().commit();
        Adres a = new Adres();
        a.setCity(b.getCity());
        a.setIdUser(b.getIdUser());
        a.setLastname(b.getLastname());
        a.setName(b.getName());
        a.setNumerDomu(b.getNumerDomu());
        a.setNumerTelefonu(b.getNumerTelefonu());
        a.setUlica(b.getUlica());
        a.setZip_code1(b.getZip_code1());
        a.setZipcode(b.getZipcode());
		return a;
	}

	@Override
	public void transfer(Integer id) throws RemoteException {
		balance+=id;
		System.out.println("dzialam balance wynosi : "+balance);
	}

}
